package com.lib.framework.helper

import android.os.CountDownTimer

/**
 * 倒计时器
 *
 * @author keanbin
 *
 * @param countDownInterval 间隔，单位：毫秒
 */
class CountDownTimerHelper(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) {

    private var mCountDownTimeListener: CountDownTimeListener? = null

    private var mMillisUntilFinished = millisInFuture

    /**
     *  是否启动
     */
    private var mIsStart = false

    override fun onFinish() {
        mIsStart = false
        mMillisUntilFinished = 0
        mCountDownTimeListener?.onTimeFinish()
    }

    override fun onTick(millisUntilFinished: Long) {
        mMillisUntilFinished = millisUntilFinished
        mCountDownTimeListener?.onProcess(millisUntilFinished)
    }

    /**
     * 启动定时器，不要用 CountDownTimer 类中的 start
     */
    fun startCountDownTimer() {
        mIsStart = true
        start()
    }

    /**
     * 关闭定时器，不要用 CountDownTimer 类中的 cancel
     */
    fun cancelCountDownTimer() {
        mIsStart = false
        cancel()
    }

    /**
     * 定时器是否启动
     */
    fun isStart(): Boolean {
        return mIsStart
    }

    /**
     * 获取剩余时间，单位毫秒
     */
    fun getMillisUntilFinished() = mMillisUntilFinished

    /**
     * 设置监听器
     */
    fun setCountDownTimeListener(l: CountDownTimeListener) {
        mCountDownTimeListener = l
    }

    /**
     * 监听接口
     */
    interface CountDownTimeListener {

        /**
         * 读秒
         * @param millisUntilFinished 还剩余多少毫秒
         */
        fun onProcess(millisUntilFinished: Long)

        /**
         * 实际结束
         */
        fun onTimeFinish()
    }
}